import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, BackHandler } from "react-native";
import { Stack, useRouter } from "expo-router";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { getRandomQuestions } from "@/mocks/questions";
import { useAppStore } from "@/store/app-store";
import { Question } from "@/types/question";
import { useTheme } from "@/hooks/useTheme";
import Button from "@/components/Button";

export default function SimulationStartScreen() {
  const router = useRouter();
  const { colors } = useTheme();
  const {
    simulationDuration,
    simulationQuestionsCount,
    selectedCategories,
    selectedDifficulties,
  } = useAppStore();
  const [questions, setQuestions] = useState<Question[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Prevent going back with hardware back button
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => true
    );

    const loadQuestions = async () => {
      try {
        const selectedQuestions = [];
        // If no categories selected, use all categories
        const categories =
          selectedCategories.length > 0 ? selectedCategories : undefined;
        // If no difficulties selected, use all difficulties
        const difficulties =
          selectedDifficulties.length > 0 ? selectedDifficulties : undefined;

        // Get random questions for each selected category
        if (categories) {
          const questionsPerCategory = Math.ceil(
            simulationQuestionsCount / categories.length
          );
          for (const category of categories) {
            const categoryQuestions = await getRandomQuestions(
              questionsPerCategory,
              category,
              undefined // Get questions of any difficulty within the category
            );
            selectedQuestions.push(...categoryQuestions);
          }
          // Trim to the exact count needed
          setQuestions(selectedQuestions.slice(0, simulationQuestionsCount));
        } else {
          // If no categories specified, just get random questions
          const randomQuestions = await getRandomQuestions(
            simulationQuestionsCount,
            undefined,
            undefined
          );
          setQuestions(randomQuestions);
        }
      } catch (error) {
        console.error('Error loading questions:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadQuestions();
    return () => backHandler.remove();
  }, []);

  const handleStartSimulation = () => {
    if (questions.length > 0) {
      router.push({
        pathname: "/simulation/question",
        params: {
          questionIds: questions.map((q) => q.id).join(","),
          duration: simulationDuration * 60, // Convert to seconds
          current: 0,
        },
      });
    }
  };
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={["bottom"]}>
      <Stack.Screen
        options={{
          title: "面试模拟",
          headerStyle: {
            backgroundColor: colors.background,
          },
          headerTintColor: colors.text,
          headerBackVisible: false,
        }}
      />
      <View style={styles.content}>
        <View style={[styles.iconContainer, { backgroundColor: "rgba(99, 102, 241, 0.1)" }]}>
          <Ionicons name="play" size={48} color={colors.primary} />
        </View>
        <Text style={[styles.title, { color: colors.text }]}>准备开始</Text>
        <Text style={[styles.description, { color: colors.subtext }]}>
          在这个模拟面试环境中，你将被问到 {questions.length} 个问题。请在时间限制内尽可能全面地回答问题。
        </Text>
        <View style={styles.infoContainer}>
          <View style={styles.infoItem}>
            <Ionicons name="time-outline" size={20} color={colors.primary} />
            <Text style={[styles.infoText, { color: colors.text }]}>
              {simulationDuration} 分钟
            </Text>
          </View>
          <View style={styles.infoItem}>
            <Text style={[styles.infoText, { color: colors.text }]}>
              {questions.length} question{questions.length !== 1 ? "s" : ""}
            </Text>
          </View>
        </View>
        <Text style={[styles.warningText, { color: colors.warning }]}>
          一旦开始，就无法暂停或退出模拟，直到完成测试。
        </Text>
      </View>
      <View style={styles.footer}>
        <Button
          title="开始模拟"
          onPress={handleStartSimulation}
          disabled={isLoading || questions.length === 0}
          loading={isLoading}
          fullWidth
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  content: {
    flex: 1,
    padding: 24,
    justifyContent: "center",
    alignItems: "center",
  },
  iconContainer: {
    width: 96,
    height: 96,
    borderRadius: 48,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 24,
  },
  title: {
    fontSize: 28,
    fontWeight: "700",
    marginBottom: 16,
    textAlign: "center",
  },
  description: {
    fontSize: 16,
    textAlign: "center",
    marginBottom: 24,
    lineHeight: 24,
  },
  infoContainer: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 24,
    gap: 24,
  },
  infoItem: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  infoText: {
    fontSize: 16,
    fontWeight: "600",
  },
  warningText: {
    fontSize: 14,
    textAlign: "center",
  },
  footer: {
    padding: 24,
  },
});
